package fl.ass.service.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import fl.ass.facade.condition.AssSchFeeDQueryCondition;
import fl.ass.facade.constant.AssFileConstant;
import fl.ass.service.dao.AssSchFeeDMapper;
import fl.ass.facade.dto.AssSchFeeDDTO;
import fl.ass.facade.dto.MessageDTO;
import fl.ass.service.po.AssSchFeeD;
import fl.ass.service.po.AssSchFeeM;
import fl.ass.service.po.PrjPrdDtl;
import fl.ass.service.service.IAssSchFeeDService;
import fl.ass.service.transform.AssSchFeeDTransform;
import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.Pager;
import cmm.service.core.framework.biz.BaseBizImpl;
import cmm.service.core.framework.dao.IBaseDao;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;

/**
 * @Description: 支付表费用项明细表 服务层接口实现
 * @Description: 类中已经实现了简单增删改查操作,可以直接使用,如果有需要重写该方法即可：
 * @Description: 1、add(TVO entity) 2、removeById(Long id) 3、modify(DTO entity) 4、selectById(Long id)	5、searchListPage(Pager page) 7、searchList(DTO dto)   
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class AssSchFeeDServiceImpl extends BaseBizImpl<AssSchFeeD, AssSchFeeDDTO, AssSchFeeDQueryCondition> implements IAssSchFeeDService {
	
	private static final Logger logger = LoggerFactory.getLogger(IAssSchFeeDService.class);
	
	@Autowired
	private AssSchFeeDMapper assSchFeeDMapper;
	
	/**
	 * TODO 自定义上传图片 API 暴露服务
	 */
	@Autowired
	private IUploadApiService uploadApiService;	
	
	/**
     * 流程API
     */
    @Autowired
    private IFlowApiService flowApiService;
    
	
	
	@Override
	public List<AssSchFeeDDTO> searchList(AssSchFeeDQueryCondition condition) throws BaseException {
		if(null == condition) return new ArrayList<AssSchFeeDDTO>();
		List<AssSchFeeD> list = this.assSchFeeDMapper.selectList(condition);
		return AssSchFeeDTransform.toDTOList(list);
	}
	
	@Override
	public IBaseDao<AssSchFeeD,AssSchFeeDQueryCondition> getDao() {
		return this.assSchFeeDMapper;
	}
	
	@Transactional
	@Override
	public MessageDTO<String> saveAssSchFeeD(Map<String, Object> map, List<AssSchFeeDDTO> assSchFeeDDTOList,FlowStartParamsDTO flowStartParamsDTO) throws BaseException {
		MessageDTO<String> response = new MessageDTO<String>();
		AssSchFeeM assSchFeeMPO = new AssSchFeeM();
		Long paySchId = (Long) map.get("paySchId");
		String paySchNo = (String) map.get("paySchNo");
		Long crtUsrId = (long) 0;
		if(assSchFeeDDTOList==null){
			response.setSuccess(false);
			response.setMessage("添加数据为空");
			return response;
		}
		// 查看数据是否存在
		//Long id = (Long) assSchFeeDMapper.selectAssSchFeeMId(paySchId);
		assSchFeeMPO.setPaySchId(paySchId);
		assSchFeeMPO.setPaySchNo(paySchNo);
		assSchFeeMPO.setFlowStatusCd(AssFileConstant.FLOW_STATUS_CD_1);
		assSchFeeMPO.setCrtTm(new Date());
		assSchFeeMPO.setIsDel(0);
		//if(id==null || id==0){
			assSchFeeDMapper.insertAssSchFeeM(assSchFeeMPO);
			Long id = assSchFeeMPO.getId();
		//}else{
		//	 assSchFeeDMapper.updateAssSchFeeM(assSchFeeMPO);
		//}
		for(int i=0;i<assSchFeeDDTOList.size();i++){
			AssSchFeeD assSchFeeDPO = AssSchFeeDTransform.toPO(assSchFeeDDTOList.get(i));
			assSchFeeDPO.setMasterId(id);
			// 如果不存在就新增  存在就更新
			Long number =  assSchFeeDMapper.selectAssSchFeeDCount(assSchFeeDPO.getId());
			if(number != null){
				assSchFeeDMapper.updateAssSchFeeD(assSchFeeDPO);
			}else{
				assSchFeeDMapper.insertAssSchFeeD(assSchFeeDPO);
				number = assSchFeeDPO.getId();
			}
			
			// 上传附件
			if(CollectionUtils.isNotEmpty(assSchFeeDDTOList.get(i).getFileList())){
				List<SysUlFilesRecDTO> fileList = assSchFeeDDTOList.get(i).getFileList();
				for (SysUlFilesRecDTO sysUlFilesRecDTO : fileList) {
					sysUlFilesRecDTO.setPkId(String.valueOf(number));
					this.uploadApiService.addSysUlFilesRec(sysUlFilesRecDTO);
				}
			}
		}
		flowStartParamsDTO.setBusinessKey(String.valueOf(paySchId));//设置流程定义ID  M的paySchId
		//流程
		FlowStartedDTO flowStartedDTO = addFlowStartGetProIntId(flowStartParamsDTO);
		if(flowStartedDTO!=null&&StringUtils.isNotBlank(flowStartedDTO.getProcInstanceId())){
            
            if(StringUtils.isNotBlank(flowStartedDTO.getNextOperUsrNames())){
            	response.setMessage("下一个节点操作人:"+flowStartedDTO.getNextOperUsrNames());
            }else{
            	response.setMessage("追加费用发起成功");
            }
			AssSchFeeM assSchFeeM = new AssSchFeeM();
			assSchFeeM.setId(id);
			assSchFeeM.setMdfUsrId(crtUsrId);
			assSchFeeM.setMdfTm(new Date());
			assSchFeeM.setFlowStatusCd(AssFileConstant.FLOW_STATUS_CD_2);
			// 修改流程的状态
			this.assSchFeeDMapper.updateAssSchFeeM(assSchFeeM);
			// 修改表明细中的 资产状态 S0108
			PrjPrdDtl prjPrdDtlPO = new PrjPrdDtl();
			prjPrdDtlPO.setPaySchId(paySchId);
			prjPrdDtlPO.setPaySchNo(paySchNo);
			//prjPrdDtlPO.setIsDel(0);
			prjPrdDtlPO.setPrdStsCd(AssFileConstant.PRJ_PRD_DTL_STATUS_CD_1);
			prjPrdDtlPO.setMdfTm(new Date());
			this.assSchFeeDMapper.updatePrjPrdDtl(prjPrdDtlPO);
			
        }else{
            response.setSuccess(false);
            response.setMessage("添加追加费用项流程发起失败");
            return response;
        }
		
		
		response.setSuccess(true);
		response.setMessage("发起追加流程成功 !");
		return response;
	}
	
	@Override
	public Pager selectAssSchFeeDById(Pager page) throws BaseException {
		List<AssSchFeeD>  AssSchFeeDList= this.assSchFeeDMapper.selectAssSchFeeDById(page);
		page.setResultList(AssSchFeeDTransform.toDTOList(AssSchFeeDList));
		return page;
	}
	
	
	/*******************************************************
	 * 发起   追加费用  流程
	 * @param flowStartParamsDTO
	 * @return
	 * @throws BaseException
	 *******************************************************/
	private FlowStartedDTO addFlowStartGetProIntId(FlowStartParamsDTO flowStartParamsDTO) throws BaseException {
    	if(StringUtils.isEmpty(flowStartParamsDTO.getBusinessKey())){
    		throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "业务数据主键必须存在!");
    	}
		if(StringUtils.isEmpty(flowStartParamsDTO.getCrtUsrId())){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "用户ID必须要存在!");
		}
		if(StringUtils.isEmpty(flowStartParamsDTO.getModelTyp())){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "流程业务分类不能为空");
		}
		if(StringUtils.isEmpty(flowStartParamsDTO.getAudStsCd())){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "流程状态不能为空");
		}
		if(StringUtils.isEmpty(flowStartParamsDTO.getWordsInTheTable())){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "动态表名标识不能为空!");
		}
		try {
			BaseLogUtils.info(logger, "addFlowStartGetProIntId", "===发起流程Start===参数:"+JSON.toJSONString(flowStartParamsDTO));

			DataResultDTO dataResultDTO = this.flowApiService.noTransFlowStart(flowStartParamsDTO);
			BaseLogUtils.info(logger, "addFlowStartGetProIntId", "===发起流程End===结果:"+JSON.toJSONString(dataResultDTO));
			FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dataResultDTO.getData();
			return flowStartedDTO;
		} catch (BaseException e) {
			BaseLogUtils.info(logger, "addFlowStartGetProIntId", "流程发起失败.DATA:"+JSON.toJSONString(flowStartParamsDTO)+",ErrorDetail:"+e.getMessage());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_605,e.getMessage());
		}catch (Exception e) {
			BaseLogUtils.info(logger, "addFlowStartGetProIntId", "流程发起失败.DATA:"+JSON.toJSONString(flowStartParamsDTO)+",ErrorDetail:"+e.getMessage());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_605,BaseExceptionConstant.BASE_EXCEPTION_CODE_605_NAME);
		}
	}

	
}

